<template>
  <div class="workprocedure-detail">
    <el-container>
      <el-header class="header-class" height="22">
        <div class="header-text">Task</div>
      </el-header>
      <el-main class="container-main">
        <el-form label-position="left" :model="taskFormData" :rules="rules" ref="validatorForm" :size="form_size"
                 :label-width="label_width" :show-message="false">
          <div class="panel">
            <div class="panel-title"><b>Working Procedure</b></div>
            <el-form-item class="duration" label="Duration:" prop="workDuration">
              <permission-slot :label-name="taskFormData.workDuration" :readOnly="!functionList.update_task">
                <el-select v-model="taskFormData.workDuration" placeholder="select">
                  <el-option
                    v-for="item in durations"
                    :key="item.appKeyValue"
                    :label="item.appKeyValue"
                    :value="item.appKeyValue">
                  </el-option>
                </el-select>
              </permission-slot>
            </el-form-item>
            <div v-if="functionList.update_task_status" class="right-panel">
              <el-button class="all-complete" size="small" @click="onAllTaskComplete">All task complete</el-button>
            </div>
            <procedure-edit-table :handler="handler" :procedureTitle="'Working Procedure'"
                                  ref="workingProcedureEditTable"
                                  :procedureType="'Working'"
                                  :show-column="workingProcedureShowColumn"
                                  :tableData.sync="wrokProcedure"></procedure-edit-table>
          </div>
          <div class="panel">
            <div class="panel-title"><b>Verification Procedure</b></div>
            <el-form-item class="duration" label="Duration:" prop="verifyDuration">
              <permission-slot :label-name="taskFormData.verifyDuration" :readOnly="!functionList.update_task">
                <el-select v-model="taskFormData.verifyDuration" placeholder="select">
                  <el-option
                    v-for="item in durations"
                    :key="item.appKeyValue"
                    :label="item.appKeyValue"
                    :value="item.appKeyValue">
                  </el-option>
                </el-select>
              </permission-slot>
            </el-form-item>
            <procedure-edit-table :procedureTitle="'Verification Procedure'" ref="verifyProcedureEditTable"
                                  :show-column="verifyProcedureShowColumn"
                                  :procedureType="'Verify'"
                                  :tableData.sync="verifyProcedure"></procedure-edit-table>

            <el-form-item label="1st verifier more than 1 party?:">
              <permission-slot :label-name="taskFormData.is1stMoreThanOneParty" :readOnly="!functionList.update_task">
                <el-radio v-model="taskFormData.is1stMoreThanOneParty" label="No">No
                </el-radio>
                <el-radio v-model="taskFormData.is1stMoreThanOneParty" label="Yes">Yes
                </el-radio>
              </permission-slot>
            </el-form-item>

            <div v-show="taskFormData.is1stMoreThanOneParty === 'Yes'">
              <permission-slot :label-name="taskFormData.firstCoordinator" :readOnly="!functionList.update_task">
                <el-form-item :label="firstCoordinatorLabel" prop="firstCoordinator">
                  <el-col :span="8">
                    <el-input v-model="taskFormData.firstCoordinator" placeholder="Personal Domain ID"></el-input>
                  </el-col>
                </el-form-item>
              </permission-slot>
            </div>
            <div v-show="taskFormData.is1stMoreThanOneParty === 'No'">
              <el-form-item :label="firstVerifierLabel" prop="txt1stVerifierDomain">
                <permission-slot :label-name="taskFormData.txt1stVerifierDomain" :readOnly="!functionList.update_task">
                  <el-col :span="8">
                    <el-input v-model="taskFormData.txt1stVerifierDomain" placeholder="Personal Domain ID"></el-input>
                  </el-col>
                </permission-slot>
              </el-form-item>
            </div>

            <el-form-item label="Contact Number:" prop="txt1stContactNumber">
              <el-col :span="8">
                <permission-slot :label-name="taskFormData.txt1stContactNumber" :readOnly="!functionList.update_task">
                  <el-input v-model="taskFormData.txt1stContactNumber" placeholder=""></el-input>
                </permission-slot>
              </el-col>
            </el-form-item>
            <el-form-item v-if="!isNewSubmission()" label="First verification result:"
                          prop="firstVerificationResult">
              <permission-slot :label-name="taskFormData.firstVerificationResult"
                               :readOnly="!functionList.update_first_verfication_info">
                <template v-for="item in radioVerificationValue">
                  <el-radio :key="item" v-model="taskFormData.firstVerificationResult" :label="item">{{item}}</el-radio>
                </template>
                <div class="comment_style">(If Partial Success or Fail, please fill in following)</div>
              </permission-slot>
            </el-form-item>
            <el-form-item v-if="taskFormData.firstVerificationResult === 'Fail'" label="Issue found:"
                          prop="firstVerificationReason">
              <permission-slot :label-name="taskFormData.firstVerificationReason"
                               :readOnly="!functionList.update_first_verfication_info">
                <el-input
                  type="textarea"
                  :rows="2"
                  placeholder=""
                  v-model="taskFormData.firstVerificationReason">
                </el-input>
              </permission-slot>
            </el-form-item>
            <el-form-item v-if="taskFormData.firstVerificationResult === 'Fail'"
                          label="Any production service/function being impacted:"
                          prop="firstVerificationImpact">
              <permission-slot :label-name="taskFormData.firstVerificationImpact"
                               :readOnly="!functionList.update_first_verfication_info">
                <el-input
                  type="textarea"
                  :rows="4"
                  placeholder=""
                  v-model="taskFormData.firstVerificationImpact">
                </el-input>
              </permission-slot>
            </el-form-item>
            <el-form-item label="2nd verifier more than 1 party? ">
              <permission-slot :label-name="taskFormData.is2ndMoreThanOneParty" :readOnly="!functionList.update_task">
                <el-radio v-model="taskFormData.is2ndMoreThanOneParty" label="No">No
                </el-radio>
                <el-radio v-model="taskFormData.is2ndMoreThanOneParty" label="Yes">Yes
                </el-radio>
              </permission-slot>
            </el-form-item>
            <div v-show="taskFormData.is2ndMoreThanOneParty === 'Yes'">
              <el-form-item :label="secondCoordinatorLabel" prop="secondCoordinator">
                <el-col :span="8">
                  <permission-slot :label-name="taskFormData.secondCoordinator" :readOnly="!functionList.update_task">
                    <el-input v-model="taskFormData.secondCoordinator" placeholder="Personal Domain ID"></el-input>
                  </permission-slot>
                </el-col>
              </el-form-item>
            </div>
            <div v-show="taskFormData.is2ndMoreThanOneParty === 'No'">
              <el-form-item :label="secondVerifierLabel" prop="txt2ndVerifierDomain">
                <el-col :span="8">
                  <permission-slot :label-name="taskFormData.txt2ndVerifierDomain"
                                   :readOnly="!functionList.update_task">
                    <el-input v-model="taskFormData.txt2ndVerifierDomain" placeholder="Personal Domain ID"></el-input>
                  </permission-slot>
                </el-col>
              </el-form-item>
            </div>
            <el-form-item label="Contact Number:" prop="txt2ndContactNumber">
              <el-col :span="8">
                <permission-slot :label-name="taskFormData.txt2ndContactNumber" :readOnly="!functionList.update_task">
                  <el-input v-model="taskFormData.txt2ndContactNumber" placeholder=""></el-input>
                </permission-slot>
              </el-col>
            </el-form-item>
            <el-form-item v-if="!isNewSubmission()"
                          label="Second verification result:" prop="verificationResult">
              <permission-slot :label-name="taskFormData.verificationResult"
                               :readOnly="!functionList.update_verfication_info">
                <template v-for="item in radioVerificationValue">
                  <el-radio :key="item" v-model="taskFormData.verificationResult" :label="item">{{item}}</el-radio>
                </template>
                <div class="comment_style">(If Partial Success or Fail, please fill in following)</div>
              </permission-slot>
            </el-form-item>
            <el-form-item v-if="taskFormData.verificationResult === 'Fail'" label="Issue found:"
                          prop="verificationReason">
              <permission-slot :label-name="taskFormData.verificationReason"
                               :readOnly="!functionList.update_verfication_info">
                <el-input
                  type="textarea"
                  :rows="2"
                  placeholder=""
                  v-model="taskFormData.verificationReason">
                </el-input>
              </permission-slot>
            </el-form-item>
            <el-form-item v-if="taskFormData.verificationResult === 'Fail'"
                          label="Any production service/function being impacted:"
                          prop="verificationImpact">
              <permission-slot :label-name="taskFormData.verificationImpact"
                               :readOnly="!functionList.update_verfication_info">
                <el-input
                  type="textarea"
                  :rows="4"
                  placeholder=""
                  v-model="taskFormData.verificationImpact">
                </el-input>
              </permission-slot>
            </el-form-item>
            <el-form-item label="Verification Deadline (HKT):" prop="dateVerificationDeadline">
              <permission-slot :label-name="readOnlyVerificationDeadLineTime"
                               :readOnly="!functionList.update_task">
                <el-date-picker
                  v-model="taskFormData.dateVerificationDeadline"
                  type="datetime"
                  placeholder="select time">
                </el-date-picker>
              </permission-slot>
            </el-form-item>
          </div>
          <div class="panel">
            <div class="panel-title"><b>Recovery Procedure</b></div>
            <el-form-item label="Require Fallback:" :label-width="'280px'">
              <permission-slot :label-name="taskFormData.isRequireFallback" :readOnly="!functionList.update_task">
                <el-radio v-model="taskFormData.isRequireFallback" label="No">No
                </el-radio>
                <el-radio v-model="taskFormData.isRequireFallback" label="Yes">Yes
                </el-radio>
              </permission-slot>
            </el-form-item>

            <el-form-item v-show="taskFormData.isRequireFallback === 'No'" label="Reason For No Fallback Action:"
                          prop="noFallbackActionReason" :label-width="'280px'">
              <el-col :span="10">
                <permission-slot :label-name="taskFormData.noFallbackActionReason"
                                 :readOnly="!functionList.update_task">
                  <el-input
                    type="textarea"
                    :rows="2"
                    placeholder=""
                    v-model="taskFormData.noFallbackActionReason">
                  </el-input>
                </permission-slot>
              </el-col>
            </el-form-item>
            <div v-show="taskFormData.isRequireFallback === 'Yes'">
              <el-form-item label="Duration:" prop="recoveryDuration" :label-width="'280px'">
                <permission-slot :label-name="taskFormData.recoveryDuration" :readOnly="!functionList.update_task">
                  <el-select v-model="taskFormData.recoveryDuration" placeholder="select">
                    <el-option
                      v-for="item in durations"
                      :key="item.appKeyValue"
                      :label="item.appKeyValue"
                      :value="item.appKeyValue">
                    </el-option>
                  </el-select>
                </permission-slot>
              </el-form-item>
              <procedure-edit-table :procedureTitle="'Recovery Procedure'" ref="recoveryProcedureEditTable"
                                    :show-column="recoveryProcedureShowColumn"
                                    :procedureType="'Recovery'"
                                    :tableData.sync="recoveryProcedure"></procedure-edit-table>
            </div>
          </div>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>
<script>
import ProcedureEditTable from '@/base-components/procedure-edit-table/ProcedureEditTable.vue'
import appKeyService from '@/service/appKey'
import moment from 'moment'
import PermissionSlot from '@/base-components/permission/PermissionSlot'
import taskService from '@/service/status'
import constants from '@/common/js/constants'
import { REQUEST_FORM } from '@/store/namespaces'
import { createNamespacedHelpers } from 'vuex'
import userService from '@/service/user'

const {mapGetters} = createNamespacedHelpers(REQUEST_FORM)

export default {
  components: {
    PermissionSlot,
    ProcedureEditTable
  },
  props: {
    taskFormData: {
      type: Object
    },
    changeRequirementData: {
      type: Object
    },
    compareStatusManagementData: {
      type: Object
    },
    functionList: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data() {
    let validateVerificationDeadline = (rule, value, callback) => {
      let selectedExceptedDate = moment(this.changeRequirementData.expectedDateChange)
      let verificationDeadlineDate = moment(value)
      if (!value) {
        callback(new Error())
      } else if (selectedExceptedDate.isAfter(verificationDeadlineDate)) {
        this.$message({
          showClose: true,
          message: 'Verification deadline cannot earilier than Expect Schedule Date and Time',
          type: 'error'
        })
        callback(new Error())
      } else {
        callback()
      }
    }

    let validateFirstCoordinator = (rule, value, callback) => {
      if (this.taskFormData.is1stMoreThanOneParty === 'Yes') {
        if (!value) {
          callback(new Error())
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    let validateTxt1stVerifierDomain = (rule, value, callback) => {
      if (this.taskFormData.is1stMoreThanOneParty === 'No') {
        if (!value) {
          callback(new Error())
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    let validateSecondCoordinator = (rule, value, callback) => {
      if (this.taskFormData.is2ndMoreThanOneParty === 'Yes') {
        if (!value) {
          callback(new Error())
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    let validateTxt2ndVerifierDomain = (rule, value, callback) => {
      if (this.taskFormData.is2ndMoreThanOneParty === 'No') {
        if (!value) {
          callback(new Error())
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    let validateNoFallbackActionReason = (rule, value, callback) => {
      if (this.taskFormData.isRequireFallback === 'No') {
        if (!value) {
          callback(new Error())
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    let validateRecoveryDuration = (rule, value, callback) => {
      if (this.taskFormData.isRequireFallback === 'Yes') {
        if (!value) {
          callback(new Error())
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    return {
      form_size: 'mini',
      label_width: '230px',
      firstVerifierLabel: '1st Verifier:',
      secondVerifierLabel: '2nd Verifier:',
      firstCoordinatorLabel: 'Change Co-ordinator:',
      secondCoordinatorLabel: 'Change Co-ordinator:',
      durations: [],
      workingProcedureShowColumn: {
        procedureDesc: {
          title: 'Procedure',
          show: true,
          readOnly: true
        },
        handledBy: {
          title: 'Change by',
          show: true,
          readOnly: true
        },
        taskStatus: {
          title: 'Task Status',
          show: true,
          readOnly: true
        },
        taskRemark: {
          title: 'Task Remark',
          show: true,
          readOnly: true
        },
        action: {
          title: 'Action',
          show: false,
          readOnly: false
        },
        addButton: {
          title: 'Add New Procedure',
          show: false
        }
      },
      verifyProcedureShowColumn: {
        procedureDesc: {
          title: 'Verification Procedure',
          show: true,
          readOnly: true
        },
        handledBy: {
          title: 'Verify by',
          show: true,
          readOnly: true
        },
        taskStatus: {
          show: false
        },
        taskRemark: {
          show: false
        },
        action: {
          title: 'Action',
          show: false,
          readOnly: false
        },
        addButton: {
          show: false,
          title: 'Add New Procedure'
        }
      },
      recoveryProcedureShowColumn: {
        procedureDesc: {
          title: 'Fallback Procedure',
          show: true,
          readOnly: true
        },
        handledBy: {
          title: 'Handle by',
          show: true,
          readOnly: true
        },
        taskStatus: {
          title: 'test',
          show: true,
          readOnly: true
        },
        taskRemark: {
          title: 'Test',
          show: true,
          readOnly: true
        },
        action: {
          title: 'Action',
          show: false,
          readOnly: false
        },
        addButton: {
          title: 'Add New Procedure',
          show: false
        }
      },
      radioVerificationValue: [
        'None', 'Success', 'Partial', 'Fail'
      ],
      rules: {
        workDuration: [
          {required: true}
        ],
        verifyDuration: [
          {required: true}
        ],
        recoveryDuration: [
          {required: true, validator: validateRecoveryDuration}
        ],
        txt1stContactNumber: [
          {required: true, trigger: 'change'}
        ],

        txt2ndContactNumber: [
          {required: true, trigger: 'change'}
        ],
        dateVerificationDeadline: [
          {required: true, validator: validateVerificationDeadline, trigger: 'change'}
        ],
        noFallbackActionReason: [
          {required: true, trigger: 'change', validator: validateNoFallbackActionReason}
        ],
        txt1stVerifierDomain: [
          {required: true, validator: validateTxt1stVerifierDomain, trigger: 'change'}
        ],
        firstCoordinator: [
          {
            required: true,
            validator: validateFirstCoordinator,
            trigger: 'change',
            judgeCondition: this.taskFormData.is2ndMoreThanOneParty
          }
        ],
        secondCoordinator: [
          {required: true, validator: validateSecondCoordinator, trigger: 'change'}
        ],
        txt2ndVerifierDomain: [
          {required: true, validator: validateTxt2ndVerifierDomain, trigger: 'change'}
        ]
      },
      handler: ''
    }
  },
  watch: {
    functionList: 'setProcedureShowColumn'
  },
  mounted() {
    this.getDurationsValue()
    this.setTaskStatusListToProcedureTable()
    this.setProcedureShowColumn()
    this.handler = userService.getUser().requesterDomainId
  },
  computed: {
    ...mapGetters({
      formStatus: 'formStatus'
    }),
    readOnlyVerificationDeadLineTime: {
      get() {
        return moment(this.taskFormData.dateVerificationDeadline).format('YYYY-MM-DD hh:mm:ss')
      }
    },
    wrokProcedure: {
      get() {
        return this.taskFormData.requestprocedures.filter(value => value.procedureType === 'Working')
      }
    },
    verifyProcedure: {
      get() {
        return this.taskFormData.requestprocedures.filter(value => value.procedureType === 'Verify')
      }
    },
    recoveryProcedure: {
      get() {
        return this.taskFormData.requestprocedures.filter(value => value.procedureType === 'Recovery')
      }
    }
  },
  methods: {
    isNewSubmission() {
      return this.formStatus === 'CREATE_FORM'
    },
    getRequestProcedureData() {
      return this.wrokProcedure.concat(this.verifyProcedure).concat(this.recoveryProcedure)
    },
    setProcedureShowColumn() {
      this.workingProcedureShowColumn = {
        procedureDesc: {
          title: 'Procedure',
          show: true,
          readOnly: !this.functionList.update_task
        },
        handledBy: {
          title: 'Change by',
          show: true,
          readOnly: !this.functionList.update_task
        },
        taskStatus: {
          title: 'Task Status',
          show: (this.functionList.update_task_status || this.functionList.update_individual_task_status) && (this.formStatus !== constants.CREATE_FORM),
          readOnly: !this.functionList.update_task_status
        },
        taskRemark: {
          title: 'Task Remark',
          show: (this.functionList.update_task_status || this.functionList.update_individual_task_status) && (this.formStatus !== constants.CREATE_FORM),
          readOnly: !this.functionList.update_task_status
        },
        action: {
          title: 'Action',
          show: this.isNewSubmission() || this.functionList.update_task,
          readOnly: false
        },
        addButton: {
          title: 'Add New Procedure',
          show: this.functionList.update_task || this.formStatus === constants.CREATE_FORM
        }
      }
      this.verifyProcedureShowColumn = {
        procedureDesc: {
          title: 'Verification Procedure',
          show: true,
          readOnly: !this.functionList.update_task
        },
        handledBy: {
          title: 'Verify by',
          show: true,
          readOnly: !this.functionList.update_task
        },
        taskStatus: {
          show: false
        },
        taskRemark: {
          show: false
        },
        action: {
          title: 'Action',
          show: this.isNewSubmission() || this.functionList.update_task,
          readOnly: false
        },
        addButton: {
          show: this.functionList.update_task || this.formStatus === constants.CREATE_FORM,
          title: 'Add New Procedure'
        }
      }
      this.recoveryProcedureShowColumn = {
        procedureDesc: {
          title: 'Fallback Procedure',
          show: true,
          readOnly: !this.functionList.update_task
        },
        handledBy: {
          title: 'Handle by',
          show: true,
          readOnly: !this.functionList.update_task
        },
        taskStatus: {
          title: 'test',
          show: false
        },
        taskRemark: {
          title: 'Test',
          show: false
        },
        action: {
          title: 'Action',
          show: this.isNewSubmission() || this.functionList.update_task,
          readOnly: false
        },
        addButton: {
          title: 'Add New Procedure',
          show: this.functionList.update_task || this.formStatus === constants.CREATE_FORM
        }
      }
    },
    validateProcedureEditTable() {
      let isValid = this.$refs['workingProcedureEditTable'].isValid() && this.$refs['verifyProcedureEditTable'].isValid()
      if (this.taskFormData.isRequireFallback === 'Yes') {
        isValid = isValid && this.$refs['recoveryProcedureEditTable'].isValid()
      }
      return isValid
    },
    durationSort(duration) {
      return duration.sort((a, b) => {
        let seq = {
          'mins': 1,
          'hrs': 2,
          'Days': 3
        }
        if (a.appKeyValue.startsWith('L') || b.appKeyValue.startsWith('M')) {
          return -1
        } else if (a.appKeyValue.startsWith('M') || b.appKeyValue.startsWith('L')) {
          return 1
        }
        let aTime = a.appKeyValue.split(' ')
        let aNumber = aTime[0]
        let aUnit = aTime[1]
        let bTime = b.appKeyValue.split(' ')
        let bNumber = bTime[0]
        let bUnit = bTime[1]
        if (aUnit === bUnit) {
          return parseFloat(aNumber) - parseFloat(bNumber)
        } else {
          return seq[aUnit] - seq[bUnit]
        }
      })
    },
    onAllTaskComplete() {
      this.wrokProcedure.forEach((item) => {
        item.taskStatus = 'Completed'
      })
    },
    async setTaskStatusListToProcedureTable() {
      if (this.workingProcedureShowColumn.taskStatus.show) {
        let data = await taskService.getStatusByType('Task')
        let taskStatusList = data.map((item) => item.statusName)
        this.$refs['workingProcedureEditTable'].setTaskStatusList(taskStatusList)
      }
    },
    async getDurationsValue() {
      let appKeys = await appKeyService.getAppKeysResult('PCRS_DURATION')
      this.durations = this.durationSort(appKeys.applicationKeyValueList)
    }
  }
}
</script>

<style scoped lang="scss">
  @import './../../../common/css/base.scss';

  .right-panel {
    float: right;
  }

  .duration {
    display: inline-block;
  }

  .container-main {
    border: 1px solid $base-header-color
  }

  .header-class {
    @include baseHeader(30px)
  }

  .header-text {
    color: #fff;
    margin-top: 5px;
    font-weight: bold;
  }

  .panel {
    padding: 0 10px 10px 15px;
    border: 1px dotted $base-header-color;
    margin-bottom: 10px;
  }

  .panel-title {
    margin-top: 10px;
    margin-bottom: 5px;
    font-size: medium;
  }

  .input-height {
    height: 20px;
  }

  .el-form-item {
    margin-bottom: 10px;
  }

  .comment_style {
    margin-left: 10px;
    color: #666;
  }

  .between-space {
    margin: 0 3px;
  }

  .text-area-bottom-space {
    margin-bottom: 5px
  }

  .comment_style {
    margin-left: 10px;
    color: #666;
  }
</style>
